package com.tn.rtdata.jmx;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * An implementation of <code>SessionInfoMXBean</code> that references the session cache in order to return session information.
 */
public class SessionInfo extends AbstractInfo implements SessionInfoMXBean
{
  private Map<String, Map<com.tn.rtdata.FillIdentity, ?>> sessionCache;
  private Map<String, Date> heartbeatCache;

  /**
   * Creates a new <code>SessionInfo</code> initialized with the <code>sessionCache</code>.
   */
  public SessionInfo(
    Map<String, Map<com.tn.rtdata.FillIdentity, ?>> sessionCache,
    Map<String, Date> heartbeatCache
  )
  {
    this.sessionCache = sessionCache;
    this.heartbeatCache = heartbeatCache;
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public List<Session> getSessions()
  {
    List<Session> sessions = new ArrayList<Session>();

    for (String sessionId : sessionCache.keySet())
    {
      sessions.add(new Session(
        sessionId,
        heartbeatCache.get(sessionId),
        convertFillIdentities(sessionCache.get(sessionId).keySet()))
      );
    }

    return sessions;
  }

  /**
   * Converts the actual <code>fillIdentities</code> to JMX friendly <code>FillIdentity</code> instances.
   */
  private List<FillIdentity> convertFillIdentities(Set<com.tn.rtdata.FillIdentity> fillIdentities)
  {
    List<FillIdentity> convertedFillIdentities = new ArrayList<FillIdentity>();

    for (com.tn.rtdata.FillIdentity fillIdentity : fillIdentities)
    {
      convertedFillIdentities.add(new FillIdentity(fillIdentity.getName(), convertFillParameters(fillIdentity.getParameters())));
    }

    return convertedFillIdentities;
  }
}
